import { Service } from 'egg';
import { createHash } from 'crypto';
import { User } from '../model/User';

/**
 * Login Service
 */
interface registerInterface {
  username: string;
  account: string;
  password: string;
  type: number;
  sex: string;
  age: number;
}
export default class Login extends Service {

  // 用于密码MD5加密
  private encryption(data: string) {
    return createHash('md5').update(data).digest('hex');
  }
  /**
   * 注册
   * @param userInfo 用户信息
   */
  public async register(userInfo: registerInterface): Promise<object> {
    const passwordMd5: string = this.encryption(userInfo.password);
    const result: object = await this.app.mysql.beginTransactionScope(async conn => {
      const userCount: Array<User> = await conn.query('select * from users where username = ? and password = ?', [ userInfo.username, passwordMd5 ]) as Array<User>;
      if (userCount.length === 0) {
        await conn.insert('users', {
          username: userInfo.username,
          password: passwordMd5,
          account: userInfo.account,
          sex: userInfo.sex,
          age: userInfo.age,
          type: userInfo.type ? userInfo.type : 0,
          created_time: new Date(),
          updated_time: new Date(),
        });
        return {
          code: 0,
          message: '注册成功',
          result: [],
        };
      }
      return {
        code: 1,
        message: '该用户已存在',
        result: [],
      };
    }, this.ctx);
    return result;
  }

  /**
   * 登录
   * @param account 账户
   * @param password 密码
   */
  public async login({ account, password }: { account: string, password: string }): Promise<object> {
    const passwordMd5: string = this.encryption(password);
    const userInfo: object = await this.app.mysql.beginTransactionScope(async conn => {
      const queryAccount = await conn.query('select * from users where account = ?', [ account ]) as Array<User>;
      if (queryAccount.length === 0) {
        return {
          code: 1,
          message: '该用户不存在',
          result: [],
        };
      }
      const queryUser = await conn.query('select * from users where account = ? and password = ?', [ account, passwordMd5 ]) as Array<User>;
      if (queryUser.length === 0) {
        return {
          code: 1,
          message: '用户名或密码不正确',
          result: [],
        };
      }
      const token = {
        account,
        password: queryUser[0].password,
        type: queryUser[0].type,
      };
      const decode = this.ctx.app.jwt.sign(token, this.config.jwt.secret);
      return {
        code: 0,
        message: '登录成功',
        result: {
          token: decode,
          type: queryUser[0].type,
          username: queryUser[0].username,
        },
      };
    }, this.ctx);
    return userInfo;
  }

  /**
   * 修改密码
   * @param param account 账户
   *              password 密码
   *              newPassword 新密码
   */
  public async editPassword({ account, password, newPassword }: { account: string, password: string, newPassword: string }) {
    const passwordMd5: string = this.encryption(password);
    const result: object = this.app.mysql.beginTransactionScope(async conn => {
      const queryAccount = await conn.query('select * from users where account = ?', [ account ]) as Array<User>;
      if (queryAccount.length === 0) {
        return {
          code: 1,
          message: '该用户不存在',
          result: [],
        };
      }
      const queryUser = await conn.query('select * from users where account = ? and password = ?', [ account, passwordMd5 ]) as Array<User>;
      if (queryUser.length === 0) {
        return {
          code: 1,
          message: '用户名或密码不正确',
          result: [],
        };
      }
      const newPasswordMd5: string = this.encryption(newPassword);
      await conn.update('users', { password: newPasswordMd5 }, {
        where: {
          account,
        },
      });
      return {
        code: 0,
        message: '修改成功',
        result: [],
      };
    }, this.ctx);
    return result;
  }
}
